const momentServer = require("../server/momentServer.js")

class MomentController {
  async create(ctx ,next){
    // 1. 获取动态内容
    const { content } = ctx.request.body

    // 2. 是谁发表动态  由token => 获取userid
    const {id} = ctx.user


    // 3. 将动态相关保存到数据库
    const result = await momentServer.create(content , id)
    if(result){
      ctx.body = {
        code:0 ,
        message:"创建用户动态成功~",
        data:result
      }
    }
  }

  async getList (ctx , next){
    const {offset ,size} = ctx.query
    // offset 偏移量  页码应该是 offset*size
    // size 页码  
    const result = await momentServer.getListServer(offset , size)
    if(result){
      ctx.body = {
        code:0 ,
        message:"获取动态成功~",
        data:result
      }
    }
  }

  async detail(ctx,next){
    const { momentId } = ctx.params
    const result = await momentServer.detailByidServer(momentId)
    if(result){
      ctx.body = {
        code:0 ,
        message:"获取详情成功~",
        data:result[0]
      }
    }
  }

  async update (ctx,next){
    // 1. 获取动态id
    const {momentId} = ctx.params
    const {content} = ctx.request.body

    const result = await momentServer.updateByIdServer(content , momentId)
    ctx.body = {
      code:0 , 
      message:"修改动态成功~",
      data:result
    }

  }

  async deleteCon(ctx,next){
    // 1. 获取动态id
    const {momentId} = ctx.params
    // 2. 执行删除语句
    const result = await momentServer.deleteByIdServer(momentId)
    if(result){
      ctx.body = {
        code:0 , 
        message:"删除动态成功~",
        data:result
      }
    }
  }


  async addLabels (ctx,next){
    // 1. 获取momentId 和 labels参数
    const { momentId } = ctx.params
    const { labels } = ctx

    // 2. 逻辑判断 已经存在的不重复添加
    for (const label of labels) {
      const isExist = await momentServer.hasLabel(momentId , label.id)
      if(!isExist){
        const result = await momentServer.addLabel(momentId , label.id)
        ctx.body = {
          code:0 , 
          message:"为动态添加标签成功~",
          result
        }
      }
    }
  }
}

module.exports = new MomentController()